/**
 * Created by wangfan on 2017/6/9.
 */
function addOneRecord(container, isValid, myFormId, names) {

    var $template = $(container).children('.row:first-child');
    var $clone = $template
        .clone()
        .removeClass('hide')
        .insertAfter($(container).find(".row:last"));


    //清空复制的input值
    $clone.find(":input").each(function (index, element) {
        if (element.tagName == "INPUT") {
            $(element).val("")
        } else if (element.tagName == "SELECT") {
            $(element).find("option:first").attr("selected", true);
        }
    });
    if (isValid) {
        for (var i = 0; i < names.length; i++) {

            var $option = $clone.find('[name=' + names[i] + ']');
            // $(myFormId).bootstrapValidator('updateStatus',$option)
            $(myFormId).bootstrapValidator('addField', $option);

        }
    }


}

function deleteOneRecord(btn, container, isValid, myFormId, names) {
    var rowNO = $(container).find(".row").length;
    if (rowNO == 1) {
        return;
    }
    var $row = btn.closest('.row');
    if (isValid) {
        for (var i = 0; i < names.length; i++) {
            $option = $row.find('[name=' + names[i] + ']');
            $(myFormId).bootstrapValidator('removeField', $option);
        }
    }
    $row.remove();
}

function regist(dltBtn, addBtn, container, isValid, myFormId, names) {


    $(document).on("click", dltBtn, function () {
        deleteOneRecord($(this), container, isValid, myFormId, names);
    });
    $(document).on("click", addBtn, function () {
        addOneRecord(container, isValid, myFormId, names);
    });
    if (isValid) {
        $(document).on('added.field.bv', function (e, data) {

            /* for(var i=0;i<names.length;i++){
             if (data.field === names[i]) {
             if ($(myFormID).find(':visible[name='+names[i]+']').length <= 1) {
             $(myFormID).find(dltBtn).attr('disabled', 'disabled');
             }
             }
             }*/

        });

        $(document).on('removed.field.bv', function (e, data) {

            for (var i = 0; i < names.length; i++) {
                if (data.field === names[i]) {
                    if ($(myFormId).find(':visible[name=' + names[i] + ']').length <= 1) {
                        $(myFormId).find(dltBtn).attr('disabled', 'disabled');
                    }
                }
            }
        });
    }

};


$(function () {

    if(localStorageFunc.getStorage("officeHistory")){
        var obj =localStorageFunc.getStorage("officeHistory");
        console.log(obj);
        $("#dataForm").find("input,textarea").each(function(){
            var name = $(this).attr('name');

            if($(this).attr("row")){
                name =name+$(this).attr("row");
            }
            if(obj[name]){
                $(this).val(obj[name]);
            }

        });

    }
    $("#inputfile").fileinput({
        showUpload : false,
        showRemove : false,
        showPreview: false,
        language : 'zh',
        maxFileCount: 1,
        elErrorContainer: ".file-error",
        allowedFileExtensions:  ["xls", "xlsx","doc", "docx", "wps"],
        maxFileSize : 2000,

    });
    $.ajax({
        url: '/commis/api/user/currentUser',
        type: "GET",
        async: false,
        dataType: 'json',
        data: {},
        success: function (response) {
            if (response.status == 0) {
                console.log("用户存在");
                user = response.data;
                userTypeId = user.userTypeId;
                var communityId = user.community.communityId;
                if (userTypeId == 4) {
                    var communityName = user.community.communityName;

                    $("#communityName").val(communityName);
                    $('#registerTime').val(getNowFormatDateShort())

                }
                $.ajax({
                    url: '/commis/api/image/getImagePathForCom',
                    type: "POST",
                    async: false,
                    dataType: 'json',
                    data: {communityId: communityId},
                    success: function (response) {
                        if (response.status == 0) {
                            $("#yinzhang").attr('src', "comImg/" + response.data.yinzhangImg);
                            $("#jwhzrImg").attr('src', "signImg/" + response.data.signImg);
                            // alert(response.data.yinzhangImg);

                        } else if (response.status == 1) {
                            alert("获取图片出错");

                        }
                    }, error: function (msg) {
                        alert("获取图片出错");
                    }
                })
            } else if (response.status == 1) {
                alert("登录用户已经过期，请重新登录");
                window.parent.location.href = "../../login.html";
            }
        }, error: function (msg) {
            alert("登录用户已经过期，请重新登录");
            window.parent.location.href = "../../login.html";
        }
    })


    // $('#dataForm').bootstrapValidator({
    //     message: 'This value is not valid',
    //     feedbackIcons: {/*输入框不同状态，显示图片的样式*/
    //         valid: 'glyphicon glyphicon-ok',
    //         invalid: 'glyphicon glyphicon-remove',
    //         validating: 'glyphicon glyphicon-refresh'
    //     },
    //     fields: {/*验证*/
    //         workexpType: {/*键名username和input name值对应*/
    //             message: '购置类型不能为空',
    //             validators: {
    //                 notEmpty: {/*非空提示*/
    //                     message: '购置类型不能为空'
    //                 }
    //             }
    //         },
    //         suppliesName: {/*键名username和input name值对应*/
    //             message: '物品名称不能为空',
    //             validators: {
    //                 notEmpty: {/*非空提示*/
    //                     message: '物品名称不能为空'
    //                 }
    //             }
    //         },
    //         unitCost: {
    //             message:'单价不能为空',
    //             validators: {
    //                 notEmpty: {
    //                     message: '单价不能为空'
    //                 }
    //             }
    //         },
    //         count: {
    //             message:'数量不能为空',
    //             validators: {
    //                 notEmpty: {
    //                     message: '数量不能为空'
    //                 },
    //                 regexp: {
    //                     regexp:/^\d+$/,
    //                     message: '必须为数字，不能有小数'
    //                 }
    //             }
    //         },
    //         sum: {
    //             message:'总金额不能为空',
    //             validators: {
    //                 notEmpty: {
    //                     message: '总金额不能为空'
    //                 },
    //                 regexp: {
    //                     regexp:/^\d+(\.\d+)?$/,
    //                     message: '必须为浮点型数字，可以有小数'
    //                 }
    //             }
    //         },
    //         paymentMode: {
    //             message:'支付方式不能为空',
    //             validators: {
    //                 notEmpty: {
    //                     message: '支付方式不能为空'
    //                 }
    //             }
    //         }
    //     }
    // });
    // var names= new Array('suppliesName','unitCost','count');
    // regist(".deleteBtn", ".addExternalLink", "#externalLink",true,'#dataForm',names);
    $('#registerTime').datetimepicker({
        language: 'zh-CN',
        format: "yyyy-mm-dd",
        minView: "month",
        autoclose: true,
        todayBtn: true


    })
    $("#sctime").text(formatStringyyyyMMddTochinese(getNowFormatDate()));


    $("#save").on("click", function () {

        var registerTime = $("input[name='registerTime']").val();
        var workexpType = $("input[name='workexpType']").val();


        var sum = $("input[name='sum']").val();
        var paymentMode = $("input[name='paymentMode']").val();
        var amount = $("input[name='amount']").val();

        if (!registerTime) {
            alert("申请时间不能为空");
            return false;
        }

        if (!workexpType) {
            alert("购置类型不能为空");
            return false;
        }

        var flag=true;
        $("input[name='no']").each(function (index, item) {
            var no = $(this).val();
            if (no) {
                var reg = /^\d+$/;
                if (!reg.test(no)) {
                    alert("明细及金额中序号必须为整数！");
                    flag = false;

                }

            }
        });
        if (!flag) {
            return false;
        }

        $("input[name='unitCost']").each(function (index, item) {
            var unitCost = $(this).val();
            if (unitCost) {
                var reg = /\d+(\.\d+)?/;
                if (!reg.test(unitCost)) {
                    alert("明细及金额中单价必须为数字！");
                    flag = false;

                }

            }
        })


        if (!flag) {
            return false;
        }

        $("input[name='count']").each(function (index, item) {
            var count = $(this).val();
            if (count) {
                var reg = /^\d+$/;
                if (!reg.test(count)) {
                    alert("明细及金额中数量必须为整数！");
                    flag = false;

                }

            }
        })
        if (!flag) {
            return false;
        }

        $("input[name='cost']").each(function (index, item) {
            var cost = $(this).val();
            if (cost) {
                var reg = /\d+(\.\d+)?/;
                if (!reg.test(cost)) {
                    alert("明细及金额中金额必须为数字！");
                    flag = false;

                }

            }
        })


        if (!flag) {
            return false;
        }


        if (!sum) {

            alert("明细及金额中总计不能为空");
            return false;

        } else {
            var reg = /\d+(\.\d+)?/;

            if (!reg.test(sum)) {
                alert("明细及金额中总计必须为数字！");
                return false;

            }

        }
        if (!paymentMode) {

            alert("预计消费方式不能为空");
            return false;

        }
        var display =$('.file-error').css('display');
       /* if(display != 'none'){
            alert("附件格式不符合要求");
            return false;
        }*/
        if ($(".has-error").length > 0){
            alert("附件格式不符合要求");
            return false;
        }
        var formData = new FormData($("#dataForm")[0]);

        if (confirm("社区领导是否已对此表内容进行审核？")) {


           /* $.ajax({
                type: "POST",
                url: "/commis/api/officeSupplies/muticreate",
                data: decodeURIComponent($('#dataForm').serialize(), true),
                async: false,
                error: function (request) {
                    alert("申报失败，请检查填写内容是否正确");
                },
                success: function (response) {
                    //接收后台返回的结果
                    if (response.status == 0) {
                        confirm("申请成功，是否关闭当前窗口？")
                        window.parent.document.getElementById("tabCloseCurrent").click();
                    } else if (response.status == 1) {
                        alert("请检查是否填写正确!");
                    }

                },

                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("数据填写不正确，请检查填写是否正确");
                }
            });*/

            $.ajax({
                url: "/commis/api/officeSupplies/muticreate",
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                error: function(request) {
                    alert("申报失败，请检查填写内容是否正确");
                },
            }).done(function (response) {
                //接收后台返回的结果
                if (response.status==0) {
                    confirm("申请成功，是否关闭当前窗口？")
                    window.parent.document.getElementById("tabCloseCurrent").click();
                } else if (response.status==1) {
                    alert("请检查是否填写正确!");
                }
            });


            //提交不了
            // $("#submitter").submit();
        } else {
            return false;
        }


    });

    $('#localSave').on("click", function () {
        $("#dataForm").find("input,textarea").each(function(){


            var name = $(this).attr('name');
            console.log(name);
            var value =$(this).val();

            if($(this).attr("row")){
                name =name+$(this).attr("row");
            }
            console.log(value);

            localStorageFunc.setStorage("officeHistory",name,value);
        });
        // // window.localStorage.formHistory=JSON.stringify(history);
    });


    $('#clear').on("click", function () {

        localStorageFunc.clearStorage("officeHistory");
        location.reload();

    });

    $("input[name='hasDetail']").click(function () {
        if ($(this).val() == "1") {


            $("#externalLink").show();
        } else {
            $("#externalLink").hide();


        }
    });


})
//设置框架
$(function () {
    $("#page_style").frame({
        float: 'left',
        menu_nav: '.Quick_operation',
        color_btn: '.skin_select',
        Sellerber_menu: '.list_content',
        Sellerber_header: '.Sellerber_header',
    });
});
$("#iframe_box").niceScroll({
    cursorcolor: "#888888",
    cursoropacitymax: 1,
    touchbehavior: false,
    cursorwidth: "5px",
    cursorborder: "0",
    cursorborderradius: "5px"
});
/*********************/
require.config({
    paths: {
        echarts: './js/dist'
    }
});